use super::conditions::MarketConditions;
use crate::agent::core::EconomicAgent;
use std::collections::HashMap;

/// 市场模拟器
pub struct MarketSimulator {
    agents: HashMap<u32, EconomicAgent>,
    conditions: MarketConditions,
    history: Vec<MarketState>,
}

/// 市场状态快照
pub struct MarketState {
    pub timestamp: i64,
    pub total_resources: f64,
    pub agent_count: usize,
}

impl MarketSimulator {
    /// 创建新市场模拟器
    pub fn new(conditions: MarketConditions) -> Self {
        MarketSimulator {
            agents: HashMap::new(),
            conditions,
            history: Vec::new(),
        }
    }

    /// 添加智能体到市场
    pub fn add_agent(&mut self, agent: EconomicAgent) {
        self.agents.insert(agent.id, agent);
    }

    /// 执行单步模拟
    pub fn step(&mut self) {
        let mut new_agents = HashMap::new();
        
        for (id, mut agent) in self.agents.drain() {
            // 根据市场条件调整行为
            agent.behavior.adjust(&self.conditions);
            
            // 执行生产/消费
            if agent.behavior.should_produce() {
                let amount = agent.behavior.production_amount();
                agent.produce(amount);
            } else {
                let amount = agent.behavior.consumption_amount();
                let _ = agent.consume(amount);
            }
            
            new_agents.insert(id, agent);
        }
        
        self.agents = new_agents;
        self.record_state();
    }

    /// 记录当前市场状态
    fn record_state(&mut self) {
        let total = self.agents.values().map(|a| a.resources).sum();
        self.history.push(MarketState {
            timestamp: chrono::Local::now().timestamp(),
            total_resources: total,
            agent_count: self.agents.len(),
        });
    }
}